//
//  EMMTabBarController.m
//  EMMApp
//
//  Created by Mac on 16/4/26.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMTabBarController.h"
#import "HYBNavigationController.h"
#import "EMMHomePageViewController.h"               //首页
#import "EMMTouristsViewController.h"               //客源
#import "EMMMyMineViewController.h"
#import "EMMHousingViewController.h"                //房源
#import "EMMNewDecisionViewController.h"            //分析
#import "EMMStatisticalAnalysisViewController.h"    //新的分析界面


@import Foundation;
@import UIKit;
@interface CYLBaseNavigationController : UINavigationController

@end
@implementation CYLBaseNavigationController

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}

@end

@interface EMMTabBarController ()

@property (nonatomic, readwrite, strong) CYLTabBarController *tabBarController;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *dTArr;


@end

@implementation EMMTabBarController


//设置Tabbar属性
- (CYLTabBarController *)tabBarController {
    _dataArr = [[NSMutableArray alloc] init];
    _dTArr = [[NSMutableArray alloc] init];

    if (_tabBarController == nil) {
        //首页
        EMMHomePageViewController *homePageViewController = [[EMMHomePageViewController alloc] init];
        HYBNavigationController *homePageNavigationController = [[HYBNavigationController alloc]
                                                                initWithRootViewController:homePageViewController];
        //客源
        EMMTouristsViewController *ptViewController = [[EMMTouristsViewController alloc] init];
        HYBNavigationController *ptNavigationController = [[HYBNavigationController alloc]
                                                          initWithRootViewController:ptViewController];
      
        //房源
        EMMHousingViewController *housViewController = [[EMMHousingViewController alloc] init];
        HYBNavigationController *housNavigationController = [[HYBNavigationController alloc]
                                                          initWithRootViewController:housViewController];
//        //分析
//        EMMNewDecisionViewController *decisionViewController = [[EMMNewDecisionViewController alloc] init];

        
        EMMStatisticalAnalysisViewController *decisionViewController = [[EMMStatisticalAnalysisViewController alloc] init];
        HYBNavigationController *decisionNavigationController = [[HYBNavigationController alloc]
                                                                initWithRootViewController:decisionViewController];
        //我的 
        EMMMyMineViewController *mineViewController = [[EMMMyMineViewController alloc] init];
        HYBNavigationController *mineNavigationController = [[HYBNavigationController alloc]
                                                            initWithRootViewController:mineViewController];
//
        CYLTabBarController *tabBarController = [[CYLTabBarController alloc] init];
        
        // 在`-setViewControllers:`之前设置TabBar的属性，设置TabBarItem的属性，包括 title、Image、selectedImage。
        [self setUpTabBarItemsAttributesForController:tabBarController];
        
        //判断是否是案场经理/经纪人
        NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];

        
        NSString *isHomePage = [userdf objectForKey:@"isHomePage"];//首页
        NSString *isCustomer = [userdf objectForKey:@"isCustomer"];//客户
        NSString *isHouses = [userdf objectForKey:@"isHouses"];//房源
        NSString *isAnalysis = [userdf objectForKey:@"isAnalysis"];//分析
        NSString *isMine = [userdf objectForKey:@"isMine"];//我的

        if ([isHomePage isEqualToString:@"1"]) {
            [_dataArr addObject:homePageNavigationController];
        }
       
        if ([isCustomer isEqualToString:@"1"]) {
            [_dataArr addObject:ptNavigationController];

        }
        if ([isHouses isEqualToString:@"1"]) {
            [_dataArr addObject:housNavigationController];

        }
        if ([isAnalysis isEqualToString:@"1"]) {
            [_dataArr addObject:decisionNavigationController];
        }
        if ([isMine isEqualToString:@"1"]) {
            [_dataArr addObject:mineNavigationController];

        }
        NSLog(@"%@",_dataArr);
        [tabBarController setViewControllers:_dataArr];
        
        
        // 更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性
        [self customizeTabBarAppearance:tabBarController];
        _tabBarController = tabBarController;
    }
    return _tabBarController;
}

- (void)setUpTabBarItemsAttributesForController:(CYLTabBarController *)tabBarController {
    
    NSDictionary *dict1 = @{
                            CYLTabBarItemTitle : @"首页",
                            CYLTabBarItemImage : @"foot_1",
                            CYLTabBarItemSelectedImage : @"foot_1a",
                            };
    NSDictionary *dict2 = @{
                            CYLTabBarItemTitle : @"客户",
                            CYLTabBarItemImage : @"foot_2",
                            CYLTabBarItemSelectedImage : @"foot_2a",
                            };
    NSDictionary *dict3 = @{
                            CYLTabBarItemTitle : @"房源",
                            CYLTabBarItemImage : @"foot_5",
                            CYLTabBarItemSelectedImage : @"foot_5a",
                            };
    NSDictionary *dict4 = @{
                            CYLTabBarItemTitle : @"分析",
                            CYLTabBarItemImage : @"foot_3",
                            CYLTabBarItemSelectedImage : @"foot_3a",
                            };
    NSDictionary *dict5 = @{
                            CYLTabBarItemTitle : @"我的",
               
                            CYLTabBarItemImage : @"foot_4",
                            CYLTabBarItemSelectedImage : @"foot_4a"
                            };
    
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *isHomePage = [userdf objectForKey:@"isHomePage"];//首页
    NSString *isCustomer = [userdf objectForKey:@"isCustomer"];//客户
    NSString *isHouses = [userdf objectForKey:@"isHouses"];//房源
    NSString *isAnalysis = [userdf objectForKey:@"isAnalysis"];//分析
    NSString *isMine = [userdf objectForKey:@"isMine"];//我的
    
    if ([isHomePage isEqualToString:@"1"]) {
        [_dTArr addObject:dict1];
    }
    
    if ([isCustomer isEqualToString:@"1"]) {
        [_dTArr addObject:dict2];
        
    }
    if ([isHouses isEqualToString:@"1"]) {
        [_dTArr addObject:dict3];
        
    }
    if ([isAnalysis isEqualToString:@"1"]) {
        [_dTArr addObject:dict4];
    }
    if ([isMine isEqualToString:@"1"]) {
        [_dTArr addObject:dict5];
    }

    tabBarController.tabBarItemsAttributes = _dTArr;
}

/**
 *  更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性
 */
- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarController {
//#warning CUSTOMIZE YOUR TABBAR APPEARANCE
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = [UIColor colorFromHexCode:@"#999999"];
    
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor colorFromHexCode:@"#fb5b3b"];
    
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorFromHexCode:@"#999999"], NSForegroundColorAttributeName, [UIFont fontWithName:@"Helvetica" size:13.0f],NSFontAttributeName,nil] forState:UIControlStateNormal];
    
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // Set the dark color to selected tab (the dimmed background)
    // TabBarItem选中后的背景颜色
    //    [self customizeTabBarSelectionIndicatorImage];
    
    // update TabBar when TabBarItem width did update
    // If your app need support UIDeviceOrientationLandscapeLeft or UIDeviceOrientationLandscapeRight， remove the comment '//'
    //如果你的App需要支持横竖屏，请使用该方法移除注释 '//'
    //    [self updateTabBarCustomizationWhenTabBarItemWidthDidUpdate];
    
    // set the bar shadow image
    // This shadow image attribute is ignored if the tab bar does not also have a custom background image.So at least set somthing.
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
    [[UITabBar appearance] setBackgroundColor:[UIColor colorFromHexCode:@"#f8f8f8"]];
    [[UITabBar appearance] setShadowImage:[UIImage imageNamed:@"tapbar_top_line"]];
    
    // set the bar background image
    // 设置背景图片
    //     UITabBar *tabBarAppearance = [UITabBar appearance];
    //     [tabBarAppearance setBackgroundImage:[UIImage imageNamed:@"tabbar_background"]];
    
    //remove the bar system shadow image
    //去除 TabBar 自带的顶部阴影
    //    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
}

- (void)updateTabBarCustomizationWhenTabBarItemWidthDidUpdate {
    void (^deviceOrientationDidChangeBlock)(NSNotification *) = ^(NSNotification *notification) {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)) {
            NSLog(@"Landscape Left or Right !");
        } else if (orientation == UIDeviceOrientationPortrait){
            NSLog(@"Landscape portrait!");
        }
        [self customizeTabBarSelectionIndicatorImage];
    };
    [[NSNotificationCenter defaultCenter] addObserverForName:CYLTabBarItemWidthDidChangeNotification
                                                      object:nil
                                                       queue:[NSOperationQueue mainQueue]
                                                  usingBlock:deviceOrientationDidChangeBlock];
}

- (void)customizeTabBarSelectionIndicatorImage {
    //Get Default TabBar Height
    UITabBarController *tabBarController;
    tabBarController = [self cyl_tabBarController] ?: [[UITabBarController alloc] init];
    CGFloat tabBarHeight = tabBarController.tabBar.frame.size.height;
    CGSize selectionIndicatorImageSize = CGSizeMake(CYLTabBarItemWidth, tabBarHeight);
    //Get initialized tabbar if exists.
    UITabBar *tabBar = [self cyl_tabBarController].tabBar ?: [UITabBar appearance];
    [tabBar setSelectionIndicatorImage:[[self class]
                                        imageFromColor:[UIColor yellowColor]
                                        forSize:selectionIndicatorImageSize
                                        withCornerRadius:0]];
}

+ (UIImage *)imageFromColor:(UIColor *)color forSize:(CGSize)size withCornerRadius:(CGFloat)radius {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Begin a new image that will be the new image with the rounded corners
    // (here with the size of an UIImageView)
    UIGraphicsBeginImageContext(size);
    
    // Add a clip before drawing anything, in the shape of an rounded rect
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];
    // Draw your image
    [image drawInRect:rect];
    
    // Get the image, here setting the UIImageView image
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    // Lets forget about that we were drawing
    UIGraphicsEndImageContext();
    return image;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
